<script lang="ts" setup>
import api from '@/common/api.js';
import base from '@/common/baseURL.js';
import { onLoad } from '@dcloudio/uni-app';
import { ref } from 'vue';
//账户信息
const accountList = ref([])
//获取抖音关联的账户
const getDouyinAccount = async () => {
	const res = await api.getDouyinAccount_API({ userId: uni.getStorageSync('userId') })
	if (res.code === 10000) {
		accountList.value = res.data.result.data
	}
}
onLoad(() => {
	getDouyinAccount()
})
const accountRef = ref()
const activeTab = ref(true)
//添加抖音帐号
const handleAdd = () => {
	getOauthConnect()
	accountRef.value.open()
}
//授权
const handleSave = () => {
	if (douyin.value.isExpire) {
		return
	};
	uni.getSetting({
		success(res) {
			if (!res.authSetting['scope.writePhotosAlbum']) {
				uni.authorize({
					scope: 'scope.writePhotosAlbum',
					success(res) {
						saveBase64ImageToPhotosAlbum()
					},
					fail() {
						uni.showModal({
							content: '请允许相册权限,拒绝将无法正常保存图片',
							showCancel: false,
							success() {
								uni.openSetting({
									success(settingdata) {
										if (settingdata.authSetting[
											'scope.writePhotosAlbum'
										]) { } else {
											console.log('获取权限失败')
											uni.showToast({
												title: "获取权限失败",
												icon: 'none',
												duration: 2000
											});
										}
									}
								})
							}
						})
					}
				})
			} else {
				saveBase64ImageToPhotosAlbum()
			}
		}
	})
};

const douyin = ref({
	token: '',
	qrcodeBase64: '',
	qrCodeUrl: '',
	countdown: 0,
	timestatus: false,
	isExpire: false,
	isRefreshQuery: false,
	clear: null,
	qrcodeIndexUrl: ''
})
const getOauthConnect = async () => {
	const res = await api.getOauthConnect_API()
	if (res.code === 10000) {
		douyin.value.token = res.data.token;
		douyin.value.qrcodeBase64 = res.data.qrcode;
		douyin.value.qrCodeUrl = "data:image/png;base64," + res.data.qrcode;
		douyin.value.qrcodeIndexUrl = res.data.qrcodeIndexUrl;
		douyin.value.countdown = 60;
		douyin.value.timestatus = true;
		douyin.value.isExpire = false;
		douyin.value.isRefreshQuery = true;
		getOauthQuery();
		douyin.value.clear = setInterval(countDown, 1000);
	}
};
const getOauthQuery = async () => {
	const res = await api.getOauthQuery_API({ code: douyin.value.token })
	if (res.code === 10000) {
		const status = res.data.status;
		if (status == "confirmed") {
			douyin.value.isRefreshQuery = false;
			uni.showModal({
				content: '恭喜您授权确认已通过',
				showCancel: false,
				success() {
					setTimeout(() => {
						uni.navigateBack()
					}, 1000)
				}
			})
		};
		if (res.code == 10001) {
			uni.showToast({
				title: '抖音账号已被绑定',
				duration: 2000,
				icon: 'none',
			})
			clearInterval(douyin.value.clear)
			setTimeout(() => {
				getOauthConnect();
			}, 2500)
		}
		if (douyin.value.isRefreshQuery) { //三秒后轮训一次
			setTimeout(() => {
				getOauthQuery();
			}, 1000)
		}
	}
};
//复制
const handleCopy = () => {
	uni.setClipboardData({
		data: douyin.value.qrcodeIndexUrl,
		success: () => {
			uni.showToast({
				title: '复制成功',
				icon: 'none'
			})
		}
	})
};
const saveBase64ImageToPhotosAlbum = () => {
	const timestamp = new Date().getTime();
	let base64 = douyin.value.qrcodeBase64; //.replace(/^data:image\/\w+;BASE64,/, ""); //去掉data:image/png;base64,
	let filePath = wx.env.USER_DATA_PATH + `/addFriends_${timestamp}_qrcode.png`;
	uni.showLoading({
		title: '保存中',
		mask: true
	})
	uni.getFileSystemManager().writeFile({
		filePath: filePath, //创建一个临时文件名
		data: base64, //写入的文本或二进制数据
		encoding: 'base64', //写入当前文件的字符编码
		success: res => {
			uni.saveImageToPhotosAlbum({
				filePath: filePath,
				success: function (res2) {
					uni.hideLoading();
					uni.showToast({
						title: "保存成功",
						icon: 'none',
						duration: 2000
					});
				},
				fail: function (err) {
					uni.hideLoading();
					console.log(err.errMsg);
					uni.showToast({
						title: "保存失败",
						icon: 'none',
						duration: 2000
					});
				}
			})
		},
		fail: err => {
			uni.hideLoading();
			console.log(err)
			uni.showToast({
				title: "创建文件失败",
				icon: 'none',
				duration: 2000
			});
		}
	})
}
//倒计时
const countDown = () => {
	if (!douyin.value.countdown) {
		douyin.value.isExpire = true;
		douyin.value.timestatus = false;
		douyin.value.isRefreshQuery = false;
		douyin.value.countdown = '刷新';
		clearInterval(douyin.value.clear);
	} else {
		--douyin.value.countdown;
	}
}
const switchTab = (tab) => {
	activeTab.value = tab;
}
let row = {}
const open = ref(false)
const handleDel = (id) => {
	row.id = id
	open.value = true

}
const handleCancel = () => {
	open.value = false
	clearInterval(douyin.value.clear)
}
const handleOk = async () => {
	const res = await api.getAccountUnbind_API({ accountAutoId: row.id })
	if (res.code === 10000) {
		uni.showToast({
			title: res.msg,
			icon: 'none',
			duration: 2000
		})
		open.value = false
		getDouyinAccount()
	}
}
</script>
<template>
	<!-- 账户管理 -->
	<view class="choose">
		<view class="choose_list">
			<view class="choose_list_item" v-for="item, key in accountList" :key="key">
				<view class="left">
					<image class="left_img" :src="item.avatar || `${base.JavaimgUrl}account.png`" mode="heightFix" />
					<text class="left_text">{{ item.nickName }}</text>
				</view>
				<view class="right" @click="handleDel(item.id)">
					<dx-icons type="minus-filled" size="25" color="#CB2D2D" />
				</view>
			</view>
		</view>
		<view class="manage_btn" @click="handleAdd">
			添加抖音账号
		</view>
		<view class="modal mask" v-show="open">
			<view class="modal_body">
				<view class="title">温馨提示</view>
				<view class="content">请确认是否要删除该抖音号吗，删除后将不再更新该账号的任何数据</view>
				<view class="btns">
					<view class="cancel" @click="handleCancel">我在想想</view>
					<view class="ok" @click="handleOk">确认删除</view>
				</view>
			</view>
		</view>
	</view>
	<uv-popup ref="accountRef" mode="bottom" round="32">
		<view class="popup" :style="{ backgroundColor: activeTab ? '#333' : '#fff' }">
			<view class="popup_head">
				<view class="tab" @click="switchTab(true)">二维码授权</view>
				<view class="tab active" @click="switchTab(false)">登录授权</view>
			</view>
			<view class="popup_desc">
				{{ activeTab ? '打开抖音APP，扫码成功后点击同意按钮完成授权' : '点击下方按钮复制链接并使用浏览器打开，成功登录账号完成授权' }}
			</view>
			<view class="popup_qrcode" v-show="activeTab">
				<image class="img" :src="douyin.qrCodeUrl" mode="heightFix" />
				<view class="popup_qrcode_mask" v-if="douyin.isExpire" @click="getOauthConnect">
					<image :src="`${base.JavaimgUrl}copy.png`" mode="heightFix" />
					<text class="text">二维码已过期，点击刷新</text>
				</view>
			</view>
			<view class="popup_hint" v-show="activeTab">请用另一部手机进行扫码授权</view>
			<view :class="{ 'popup_state': true, expires: douyin.isExpire }" v-show="activeTab">
				{{ !douyin.isExpire ? douyin.countdown : '已过期' }}
			</view>
			<view class="popup_introduce">
				<text style="color: #D6D6D6;margin-bottom: 16rpx;">授权成功您可以:</text>
				<text class="text">同步账号基础信息及查看账号运营数据；</text>
				<text class="text">获取联盟售卖订单数据；</text>
				<text class="text">获取高佣商品并添加至橱窗，提升收益。</text>
			</view>
			<view class="popup_btn">
				<view v-if="activeTab" @click="handleSave" style="display: flex;align-items: center;">
					<image class="img" :src="`${base.JavaimgUrl}copy.png`" mode="heightFix" />
					<text class="text">保存二维码</text>
				</view>
				<view v-else @click="handleCopy"
					style="display: flex;align-items: center;justify-content: center;flex: 1;">
					<image class="img" :src="`${base.JavaimgUrl}copy.png`" mode="heightFix" />
					<text class="text">复制链接</text>
				</view>
			</view>
		</view>
	</uv-popup>
</template>
<style scoped>
.choose {
	min-height: 100vh;
	background-color: #F4F6F9;
	overflow: hidden;
	position: relative;
}

.choose_list {
	margin: 24rpx 24rpx 0;
}

.choose_list_item {
	display: flex;
	align-items: center;
	justify-content: space-between;
	height: 132rpx;
	background: #FFF;
	border-radius: 8rpx;
	margin-top: 24rpx;
	padding: 0 42rpx 0 24rpx;
}

.choose_list_item .left {
	display: flex;
	align-items: center;
}

.choose_list_item .left_img {
	width: 68rpx;
	height: 68rpx;
	border-radius: 50%;
	vertical-align: middle;
}

.choose_list_item .left_text {
	font-size: 30rpx;
	font-family: PingFang SC, PingFang SC;
	color: #333;
	margin-left: 24rpx;
}

.choose_list_item .right_img {
	width: 40rpx;
	height: 40rpx;
	vertical-align: middle;
}

.manage_btn {
	position: absolute;
	left: 24rpx;
	bottom: 160rpx;
	display: flex;
	align-items: center;
	justify-content: center;
	border-radius: 16rpx;
	width: 702rpx;
	height: 88rpx;
	background: #7F7FE9;
	font-size: 30rpx;
	font-family: PingFang SC, PingFang SC;
	color: #FFF;
}

.mask {
	position: fixed;
	top: 0;
	left: 0;
	width: 100%;
	height: 100vh;
	background-color: rgba(0, 0, 0, 0.8);
}

.modal_body {
	position: relative;
	top: 50%;
	left: 50%;
	transform: translate(-50%, -50%);
	width: 630rpx;
	background: #FFF;
	border-radius: 32rpx;
	opacity: 1;
}

.modal_body .title {
	font-size: 30rpx;
	font-family: PingFang SC, PingFang SC;
	color: #333;
	padding-top: 48rpx;
	text-align: center;
}

.modal_body .content {
	font-size: 30rpx;
	font-family: PingFang SC, PingFang SC;
	color: #333;
	margin: 24rpx 24rpx 48rpx;
	text-align: center;
}

.modal_body .btns {
	display: flex;
	align-content: center;
	justify-content: center;
	padding-bottom: 48rpx;
}

.modal_body .btns .cancel {
	padding: 16rpx 68rpx;
	background: #F5F5F5;
	font-size: 26rpx;
	font-family: PingFang SC, PingFang SC;
	font-weight: 400;
	color: #999;
	margin-right: 48rpx;
}

.modal_body .btns .ok {
	padding: 16rpx 68rpx;
	background: #FDEAEA;
	font-size: 26rpx;
	font-family: PingFang SC, PingFang SC;
	font-weight: 400;
	color: #EC282F;
}

.popup {
	height: 90vh;
	background-color: #333;
	border-radius: 32rpx 32rpx 0 0;
}

.popup_head {
	display: flex;
	align-items: center;
	justify-content: space-between;
	margin-bottom: 40rpx;
}

.popup_head .tab {
	flex: 1;
	display: flex;
	align-items: center;
	justify-content: center;
	height: 64rpx;
	font-size: 26rpx;
	font-family: PingFang SC, PingFang SC;
	border-radius: 32rpx 0 0 0;
	color: #FFF;
	background: #333;
}

.popup_head .active {
	background-color: #fff;
	color: #333;
	border-radius: 0 32rpx 0 0;
}

.popup_desc {
	text-align: center;
	height: 68rpx;
	line-height: 68rpx;
	font-size: 22rpx;
	font-family: PingFang SC, PingFang SC;
	color: #333;
	background-color: #C2C2C2;
	border-radius: 8rpx;
	margin: 0 26rpx 48rpx;
}

.popup_qrcode {
	position: relative;
	width: 460rpx;
	height: 476rpx;
	text-align: center;
	margin: 0 auto;
}

.popup_qrcode .img {
	width: 460rpx !important;
	height: 476rpx;
}

.popup_qrcode_mask {
	position: absolute;
	top: 0;
	left: 0;
	display: flex;
	align-items: center;
	flex-direction: column;
	justify-content: center;
	width: 100%;
	height: 100%;
	background-color: rgba(0, 0, 0, 0.8);
}

.popup_qrcode_mask image {
	width: 57rpx;
	height: 57rpx;
	margin-bottom: 14rpx;
}

.popup_qrcode_mask .text {
	font-size: 30rpx;
	font-family: PingFang SC, PingFang SC;
	color: #FFF;
}

.popup_hint {
	margin-top: 32rpx;
	text-align: center;
	font-size: 30rpx;
	font-family: PingFang SC, PingFang SC;
	color: #FFF;
}

.popup_state {
	width: 460rpx;
	height: 62rpx;
	text-align: center;
	line-height: 62rpx;
	background-color: #4A4A6A;
	font-size: 30rpx;
	font-family: PingFang SC, PingFang SC;
	color: #7F7FE9;
	border-radius: 66rpx;
	margin-bottom: 40rpx;
	margin: 32rpx auto 40rpx;
}

.popup .expires {
	background-color: #6A4A56 !important;
	color: #E97FA7 !important;
}

.popup_introduce {
	display: flex;
	flex-direction: column;
	margin-left: 78rpx;
}

.popup_introduce .text {
	display: flex;
	align-items: center;
	color: #C2C2C2;
	font-size: 24rpx;
	margin-bottom: 8rpx;
	position: relative;
	padding-left: 25rpx;
}

.popup_introduce .text::before {
	position: absolute;
	right: 0;
	left: 0;
	content: '';
	width: 16rpx;
	height: 16rpx;
	background: #7F7FE9;
	border-radius: 50%;
}

.popup_btn {
	/* 		position: absolute;
		left: 24rpx;
		bottom: 60rpx; */
	display: flex;
	align-items: center;
	justify-content: center;
	margin: 100rpx auto;
	border-radius: 16rpx;
	width: 702rpx;
	height: 88rpx;
	background: #7F7FE9;
}

.popup_btn .img {
	width: 44rpx;
	height: 44rpx;
	vertical-align: middle;
	margin-right: 8rpx;
}

.popup_btn .text {
	font-size: 30rpx;
	font-family: PingFang SC, PingFang SC;
	color: #FFF;
}
</style>